<?php

namespace App\Http\Controllers\QH_Api;

use App\Http\Controllers\TK_Api\ApiBaseController;
use App\Models\Coupon;
use App\Models\Course;
use App\Models\CourseColumn;
use App\Models\Document;
use App\Models\GroupBuy;
use App\Models\GroupBuyData;
use App\Models\LearnVideo;
use App\Models\NetCourse;
use App\Models\Qh_Course;
use App\Models\Qh_MiniProgramComponent;
use Carbon\Carbon;
use Illuminate\Http\JsonResponse;
use RedisException;

class CourseColumnController extends ApiBaseController
{

    /**
     * 获取详情
     * @return JsonResponse|object
     * @throws RedisException
     * @throws \Exception
     */
    public function getInfo()
    {
        $id = request('id');

        $model = CourseColumn::where('id', $id)->first();

        if (!$model) throw new \Exception('专栏已下架');

        $valueJsonComponents = $model->components;
        $components = [];
        $componentsSorts = array();
        foreach ($valueJsonComponents as $key => $row) {
            $componentsSorts[$key] = $row['sort'];
        }
        array_multisort($componentsSorts, SORT_ASC, $valueJsonComponents);

        $couponCount = 0;
        foreach ($valueJsonComponents as $component) {
            $c = Qh_MiniProgramComponent::find($component['id']);
            if (!$c) continue;
            $c->data = qhMiniProgramComponentDataFormat($c);
            if (($c->componentName == 'coupon' || $c->componentName == 'document') && $c->data == null) continue;
            if (($c->componentName == 'coupon')) $couponCount += 1;
            $components[] = $c;
        }
        $model->components = $components;

        // 获取优惠券数据
        $model->coupon = Coupon::whereIn('id', $model->coupon_ids ?? [])
            ->where('is_active', 1)
            ->where('stop_get', '>', now()->subMinutes(5))
            ->where('end_use_at', '>', now()->subMinutes(5))
            ->get();

        // 获取优惠券数量
        $model->couponCount = count($model->coupon);

        // 获取专栏下的拼团数据
        $model->groupBuy = null;
        //$model->groupBuy = GroupBuy::where('type', 1)
        //    ->where('data_id', $model->id)
        //    ->with(['list' => function ($q) {
        //        $q->select([
        //            'id',
        //            'group_buy_id',
        //            'leader_id',
        //            'leader_avatar',
        //            'leader_nickname',
        //            'original_price',
        //            'leader_price',
        //            'member_price',
        //            'member_num',
        //            'member_count',
        //            'status',
        //            'start_at',
        //            'end_at'
        //        ])
        //            ->where('status', 1)
        //            ->orderByDesc('created_at');
        //    }])
        //    ->first();

        // 获取专栏下的资源
        $resource = $model->resource;
        $resource2 = [
            'courses' => [],
            'documents' => [],
            'learn_videos' => [],
        ];
        if (!empty($resource['courses'])) {
            $resource2['courses'] = Qh_Course::whereIn('id', $resource['courses'])->get();
        }
        if (!empty($resource['documents'])) {
            $resource2['documents'] = Document::select([
                'id',
                'title',
                'downloadCount',
                'viewCount',
                'thumb',
                'print',
                'fileFormat',
                'fileSize',
                'amount'
            ])->whereIn('id', $resource['documents'])->get();
        }
        //$model->watchUserCount = 0;
        if (!empty($resource['learn_videos'])) {
            $resource2['learn_videos'] = LearnVideo::whereIn('id', $resource['learn_videos'])->get();
            //foreach ($resource2['learn_videos'] as $video) {
            //    $model->watchUserCount += $video->learn_count;
            //}
        }
        $model->resource2 = $resource2;

        // 计算最低价
        $minCouponPrice = 0;
        foreach ($model->coupon as $coupon) {
            if ($coupon->unlock_price > $model->price) continue;
            if ($minCouponPrice == 0 || $coupon->free_price < $minCouponPrice) $minCouponPrice = $coupon->free_price;
        }
        $model->minPrice = round($model->price - $minCouponPrice, 2);

        $expireAt = getCourseColumnExpireAt($model);
        if ($expireAt->diffInYears(now()) > 90) $model->expireAt = '长期';
        else $model->expireAt = $expireAt->format('Y.m.d');

        return $this->restful($model);
    }

    /**
     * 获取拼团数据
     * @return JsonResponse|object
     * @throws \Exception
     */
    public function getCourseColumnGroupBuyList()
    {
        $courseColumnId = request('id');

        $groupBuys = GroupBuy::where('type', 1)
            ->where('data_id', $courseColumnId)
            ->with([
                'list' => function ($q) {
                    $q->select([
                        'id',
                        'group_buy_id',
                        'leader_id',
                        'leader_avatar',
                        'leader_nickname',
                        'original_price',
                        'leader_price',
                        'member_price',
                        'member_num',
                        'member_count',
                        'member_ids',
                        'status',
                        'start_at',
                        'end_at'
                    ])
                        ->where('status', 1)
                        ->orderByDesc('created_at');
                },
                'courseColumn' => function ($q) {
                    $q->select(['id', 'name']);
                }
            ])
            ->first();

        if (!$groupBuys) throw new \Exception('活动已下线');

        return $this->restful($groupBuys);
    }

}
